﻿using MesDAL.DBInfo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MesBLL.Common
{
    public class CommonService<T> : IDisposable where T : class, new()
    {
        public ServerEFModel serverEFModel = new ServerEFModel();

        public async Task<T> AddAsync(T t)
        {
            serverEFModel.Set<T>().Add(t);
            await serverEFModel.SaveChangesAsync();
            return t;
        }

        public async Task<T> EditAsync(T t)
        {
            serverEFModel.Entry<T>(t).State = System.Data.Entity.EntityState.Modified;
            await serverEFModel.SaveChangesAsync();
            return t;
        }

        public async Task<bool> DeleteAsync(int id)
        {
            try
            {
                var t = serverEFModel.Set<T>().Find(id);
                serverEFModel.Entry(t).State = System.Data.Entity.EntityState.Deleted;
                await serverEFModel.SaveChangesAsync();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public IQueryable<T> GetAll()
        {
            return serverEFModel.Set<T>().AsNoTracking();
        }


        public void Dispose()
        {
            serverEFModel.Dispose();
        }
    }
}
